﻿// Sequin.Sequences.SymbolMapper
//
// (c) 2011 Arthur Pitman
//
// Part of the Sequin Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License (Version 2.1) as published by the Free Software Foundation.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License (Version 2.1) along with this library; if not, write to the 
// Free Software Foundation, Inc., 
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
// or see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sequin.Sequences
{
	/// <summary>
	/// Maps symbols (i.e. textual strings) to ids (ints)
	/// Basic implementation of <see cref="ISymbolMapper"/>
	/// </summary>
	public class SymbolMapper : ISymbolMapper
	{
		/// <summary>
		/// Used to map the text symbols to ids
		/// </summary>
		protected Dictionary<string, int> symbolLookupTable;

		/// <summary>
		/// Used to map ids back to text symbols
		/// </summary>
		protected List<string> reverseSymbolLookupTable;

		/// <summary>
		/// Initializes a new <see cref="SymbolMapper"/> instance
		/// </summary>
		public SymbolMapper()
		{
			symbolLookupTable = new Dictionary<string, int>();
			reverseSymbolLookupTable = new List<string>();
		}

		/// <summary>
		/// Converts a <see cref="string"/> symbol to an <see cref="int"/> id
		/// </summary>
		/// <param name="symbol">The <see cref="string"/> symbol</param>
		/// <returns>The <see cref="int"/> id</returns>
		public int SymbolToId(string symbol)
		{
			int i = 0;
			if (!symbolLookupTable.TryGetValue(symbol, out i))
			{
				i = symbolLookupTable.Count;
				symbolLookupTable.Add(symbol, i);
				reverseSymbolLookupTable.Add(symbol);
			}
			return i;
		}

		/// <summary>
		/// Converts an <see cref="int"/> id to a <see cref="string"/> symbol
		/// </summary>
		/// <param name="id">The <see cref="int"/> id</param>
		/// <returns>The <see cref="string"/> symbol</returns>
		public string IdToSymbol(int id)
		{
			return reverseSymbolLookupTable[id];
		} 
	}

}
